package com.sunmouse.toolkit.widget.shader;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ComposeShader;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;

import com.sunmouse.toollib.utils.LogUtils;
import com.sunmouse.toolkit.R;

/**
 * Created by Administrator on 2017/9/13 0013.
 */
public class GradientView extends View {
    private Paint mPaint;
    private int w;
    private int h;

    public GradientView(Context context) {
        this(context, null);
    }

    public GradientView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initProperty();
    }

    private void initProperty() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);

        DisplayMetrics metrics = getResources().getDisplayMetrics();
        w = metrics.widthPixels;
        h = metrics.heightPixels;
        mPaint.setShader(generateShader(5));
        LogUtils.d("----w=" + w + " ：h=" + h);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawCircle(w / 2, h / 2, w / 2, mPaint);
    }

    /**
     * generate a shader
     *
     * @param i
     * @return
     */
    private Shader generateShader(int i) {
        switch (i) {
            case 1:
                Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
                return new BitmapShader(mBitmap, Shader.TileMode.MIRROR, Shader.TileMode.REPEAT);
            case 2:
                return new LinearGradient(0, 0, w, h, Color.RED, Color.WHITE, Shader.TileMode.CLAMP);
            case 3:
                return new RadialGradient(w / 2, h / 2, w / 2, Color.RED, Color.WHITE, Shader.TileMode.CLAMP);
            case 4:
                return new SweepGradient(w / 2, h / 2, Color.RED, Color.WHITE);
            case 5:
                return new ComposeShader(generateShader(1), generateShader(3), PorterDuff.Mode.ADD);
        }

        return null;
    }
}
